package com.lx.idea.service;

import com.alibaba.fastjson.JSON;
import com.lx.idea.common.config.ElasticsearchConfig;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.DocWriteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author ybb
 * @Description
 * @Date 2021/9/16 16:55
 */
@Component
@Slf4j
public class ESService {

    @Autowired
    ElasticsearchConfig elasticsearchConfig;

    /**
     * @Param
     * @return
     */
    public void save(String index,String type,Object object){
        try {
            IndexRequest request = new IndexRequest(index,type);
            request.opType(DocWriteRequest.OpType.INDEX).source(JSON.toJSONString(object), XContentType.JSON);
            elasticsearchConfig.clientDev().index(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            log.error("ES存储异常 => {},{}",index,type);
            e.printStackTrace();
        }
    }

    public Map  analysisCount(String index,String type,String minDate,String maxDate){

        SearchRequest searchRequest =new SearchRequest(index);
        searchRequest.types(type);
        QueryBuilder queryBuilder = QueryBuilders.rangeQuery("startTimeStr.keyword")
                .from(minDate).to(maxDate);
        searchRequest.source(new SearchSourceBuilder().query(queryBuilder));
        Map result = new HashMap<>();
        Map<String,Long> map = new HashMap<>();
        List<String> keys = new ArrayList<>();
        List<Long> vals = new ArrayList<>();
        try {
            SearchHits searchHits = elasticsearchConfig.clientDev().search(searchRequest, RequestOptions.DEFAULT).getHits();
            for (int i=0;i<searchHits.getHits().length;i++){
                SearchHit hit =  searchHits.getHits()[i];
                String str = hit.getSourceAsMap().get("startTimeStr").toString().substring(0,11);
                if (map.containsKey(str)){
                    map.put(str,map.get(str)+1);
                }else {
                    map.put(str,1L);
                }
            }
            map.keySet().forEach(key -> {
                keys.add(key);
                vals.add(map.get(key));
            });
            result.put("date",keys);
            result.put("count",vals);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }
}
